# -*- coding: utf-8 -*-
from flask import Blueprint,request,redirect,jsonify
from common.libs.Helper import osp_render,getCurrentDate
from application import app,db

from common.libs.UrlManager import UrlManager
from common.libs.user.UserService import UserService

from common.models.User import User
from sqlalchemy import or_
route_account = Blueprint( 'account_page',__name__ )

@route_account.route( "/index" )
def index():
    resq_data = {}
    req = request.values
    query = User.query
    count = query.count()#总共多少条记录
    #搜索功能实现or_表示定义了一个规则
    if "mix_kw" in req:
        rule = or_(User.nickname.ilike('%{0}%'.format(req['mix_kw'])),
                   User.mobile.ilike('%{0}%'.format(req['mix_kw'])))
        query = query.filter(rule)
    # status的查询
    if 'status' in req and int (req['status']) > -1 : #status默认为-1
        query = query.filter(User.status == req['status'])

    app.logger.info(request.full_path)

    list = query.order_by( User.uid.desc() ).all()#全量查询，倒叙排列
    resq_data['list']=list
    resq_data['search_con'] = req
    resq_data['count']=count
    resq_data['status_mapping'] = app.config['STATUS_MAPPING']
    return osp_render( "/account/index.html",resq_data)

@route_account.route( "/info" )
def info():
    resq_data = {}
    req = request.args
    uid = int (req.get('id', 0))
    reback_url = UrlManager.buildUrl('account/index')#自定义语句
    if uid < 1:
        return  redirect (reback_url)

    # 1、查询用户是否存在
    info = User.query.filter_by (uid = uid).first()
    if not info:
        return redirect(reback_url)

    # 2、将user信息作为参数传入前端展示
    resq_data['info'] = info
    return osp_render( "account/info.html" ,resq_data)

@route_account.route( "/set" , methods = ["GET", "POST"])
def set():
    default_pwd = "******"
    if request.method == 'GET':#直接渲染
        resq_data = {}
        req = request.args
        uid = int( req.get('id', 0) )
        user_info = None
        if uid:
            user_info = User.query.filter_by(uid = uid).first()
        resq_data['user_info'] = user_info
        return osp_render( "account/set.html" ,resq_data)

    resq = {'code':200, 'msg':'操作成功~~','data':{}}
    req = request.values
    #1、参数获取
    uid = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    email = req['email'] if 'email' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''
    #2、有效性校验

    if nickname is None or len(nickname) < 1:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的姓名~'
        return jsonify (resq)
    if email is None or len(email) < 1:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的邮箱~'
        return jsonify (resq)
    if mobile is None or len(mobile) < 1:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的手机号~'
        return jsonify (resq)
    if login_name is None or len(login_name) < 1:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的登录名~'
        return jsonify (resq)
    if login_pwd is None or len(login_pwd) < 6:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的登录密码~'
        return jsonify (resq)

    #3、检验重复性<排除当前用户本身用户本身User.uid != id，其他用户的login_nama不能重复>
    has_in = User.query.filter(User.login_name == login_name, User.uid != id).first()
    if has_in:
        resq['code'] = -1
        resq['msg'] = '该登录名已存在，请换一个试试~'
        return  jsonify(resq)

    user_info = User.query.filter_by(uid = uid).first()
    # 新增还是编辑的判断，判断用户有没有，有则是编辑(原则就是根据UID）
    if user_info:
        model_user = user_info#还是原来的那个用户对象
    else:
        #如果新增则需要初始化User()
        model_user = User()#是否新增的关键是这一行代码
        #创建时间和随机字符串只能生成一次
        model_user.created_time = getCurrentDate()
        model_user.login_salt = UserService.geneSalt()
    # 4、写入数据库
    model_user.nickname = nickname
    model_user.email = email
    model_user.mobile = mobile
    model_user.login_name = login_name

    #如果密码不等于默认的6个*,才进行保存
    if login_pwd != default_pwd:
         model_user.login_pwd = UserService.genePwd(login_pwd, model_user.login_salt)

    model_user.updated_time = getCurrentDate()

    db.session.add(model_user)
    db.session.commit()

    return jsonify(resq)

@route_account.route( "/ops" , methods = ["GET", "POST"])
def ops():
    resq = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values

    id= req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resq['code'] = -1
        resq['msg'] = '请选择要操作的账号~'
        return jsonify(resq)

    if act not in ['remove', 'recover']:
        resq['code'] = -1
        resq['msg'] = '操作有误，请重试~'
        return jsonify(resq)

    info = User.query.filter_by(uid=id).first()

    if not info:
        resq['code'] = -1
        resq['msg'] = '制定账号不存在~'
        return jsonify(resq)
    if act == 'remove':
        info.status = 0
    elif act == 'recover':
        info.status = 1
    #更新操作事件
    info.update_time = getCurrentDate()
    #更新数据库
    db.session.add(info)
    db.session.commit()
    return jsonify(resq)